package com.eco.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.eco.annotation.AuthToken;
import com.eco.entity.Sensor;
import com.eco.service.SensorService;

import java.util.LinkedHashMap;
import java.util.List;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
public class SensorController {

    @Autowired
    private SensorService scanService;

    @GetMapping({"/getSensorData"})
    public JSONObject getSensorData(String startDate, String endDate, @RequestParam(defaultValue = "1") Integer pageNum,@RequestParam(defaultValue = "10") Integer pageSize) {
        JSONObject result = new JSONObject();
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            log.error("请选择时间段");
            result.put("msg", "请选择时间段");
            result.put("status", Boolean.valueOf(false));
            result.put("data", null);
            return result;
        }

        IPage<Sensor> page = this.scanService.findByStime(startDate, endDate, pageNum, pageSize);
        List<Sensor> sensorList = page.getRecords();
        if (CollectionUtils.isEmpty(sensorList)) {
            log.error("未查询到流速数据");
            result.put("msg", "未查询到流速数据");
            result.put("status", Boolean.valueOf(true));
            result.put("data", null);
            return result;
        }
        JSONArray datas = new JSONArray();
        sensorList.stream().forEach(scan -> {
            JSONObject data = new JSONObject(new LinkedHashMap<>());
            data.put("createTime", scan.getStime());
            data.put("tmp", scan.getTmp());
            data.put("phg", scan.getPhg());
            data.put("rdo", scan.getRdo());
            data.put("zd", scan.getZd());
            data.put("gcjksw", scan.getGcjksw());
            data.put("gcjkls", scan.getGcjkls());
            data.put("fsjksw", scan.getFsjksw());
            data.put("fsjkls", scan.getFsjkls());
            data.put("cksw", scan.getCksw());
            data.put("ckls", scan.getCkls());
            datas.add(data);
        });
        log.info("查询流速数据成功");
        result.put("status", Boolean.valueOf(true));
        result.put("data", datas);
        result.put("total",page.getTotal());
        return result;
    }
}
